const pool = require('../config/db')
const Dish = require('../models/dishModel')

/**
 * 菜品控制器
 */
const dishController = {
  /**
   * 菜品分页条件查询
   */
  getAllDishes: async (req, res) => {
    try {
      const {
        name,
        categoryIds, // 数组参数
        tasteIds, // 数组参数
        difficulty,
        cookTime,
        pageNumber = 1,
        pageSize = 10,
      } = req.body // 从 body 获取参数

      // 确保数组类型
      const processedCategoryIds = Array.isArray(categoryIds) ? categoryIds : []
      const processedTasteIds = Array.isArray(tasteIds) ? tasteIds : []

      const result = await Dish.findAll({
        name,
        categoryIds: processedCategoryIds,
        tasteIds: processedTasteIds,
        difficulty,
        cookTime,
        page: parseInt(pageNumber),
        pageSize: parseInt(pageSize),
      })
      res.json({
        code: 1,
        msg: 'success',
        data: result,
      })
    } catch (error) {
      console.error('查询菜品列表出错:', error)
      res.status(500).json({
        code: 0,
        msg: '查询菜品列表失败',
        data: null,
      })
    }
  },

  /**
   * 菜品详情查询
   */
  getDishById: async (req, res) => {
    try {
      const dishId = parseInt(req.params.id)
      const dish = await Dish.findById(dishId)

      if (!dish) {
        return res.status(404).json({
          code: 0,
          msg: '菜品不存在',
          data: null,
        })
      }

      res.json({
        code: 1,
        msg: 'success',
        data: dish,
      })
    } catch (error) {
      console.error('查询菜品详情出错:', error)
      res.status(500).json({
        code: 0,
        msg: '查询菜品详情失败',
        data: null,
      })
    }
  },

  /**
   * 创建菜品
   */
  createDish: async (req, res) => {
    try {
      let { name, difficulty, cookTime, categories, tastes, steps, mainImage, ingredients } =
        req.body

      // 预处理 steps，将 duration_value 为 "" 的转为 null，单位默认“分钟”
      if (Array.isArray(steps)) {
        steps = steps.map((group) => ({
          ...group,
          steps: Array.isArray(group.steps)
            ? group.steps.map((step) => ({
                ...step,
                duration_value: step.duration_value === '' ? null : step.duration_value,
                duration_unit: step.duration_unit || '分钟',
              }))
            : [],
        }))
      }

      // 预处理 ingredients
      if (!Array.isArray(ingredients)) {
        ingredients = []
      }

      // 验证必填字段
      if (
        !name ||
        !difficulty ||
        !cookTime ||
        !categories ||
        !categories.length ||
        !steps ||
        !steps.length ||
        !ingredients ||
        !ingredients.length
      ) {
        return res.status(400).json({
          code: 0,
          msg: '缺少必要参数',
          data: null,
        })
      }

      const dishId = await Dish.create({
        name,
        difficulty,
        cookTime,
        categories,
        tastes,
        steps,
        mainImage,
        ingredients,
      })

      res.status(201).json({
        code: 1,
        msg: 'success',
        data: { dishId },
      })
    } catch (error) {
      console.error('创建菜品出错:', error)
      res.status(500).json({
        code: 0,
        msg: '创建菜品失败',
        data: null,
      })
    }
  },

  /**
   * 更新菜品
   */
  updateDish: async (req, res) => {
    try {
      const dishId = parseInt(req.params.id)
      const { name, difficulty, cookTime, categories, tastes, steps, mainImage, ingredients } =
        req.body

      // 预处理 ingredients
      let safeIngredients = Array.isArray(ingredients) ? ingredients : []

      // 验证必填字段
      if (
        !name ||
        !difficulty ||
        !cookTime ||
        !categories ||
        !categories.length ||
        !steps ||
        !steps.length ||
        !safeIngredients ||
        !safeIngredients.length ||
        steps.some(
          (group) =>
            !group.steps || !group.steps.length || group.steps.some((step) => !step.duration_unit)
        )
      ) {
        return res.status(400).json({
          code: 0,
          msg: '缺少必要参数',
          data: null,
        })
      }

      // 检查菜品是否存在
      const exists = await Dish.exists(dishId)
      if (!exists) {
        return res.status(404).json({
          code: 0,
          msg: '菜品不存在',
          data: null,
        })
      }

      await Dish.update(dishId, {
        name,
        difficulty,
        cookTime,
        categories,
        tastes,
        steps,
        mainImage,
        ingredients: safeIngredients,
      })

      res.json({
        code: 1,
        msg: 'success',
        data: null,
      })
    } catch (error) {
      console.error('更新菜品出错:', error)
      res.status(500).json({
        code: 0,
        msg: '更新菜品失败',
        data: null,
      })
    }
  },

  /**
   * 删除菜品
   */
  deleteDish: async (req, res) => {
    try {
      const dishId = parseInt(req.params.id)

      // 检查菜品是否存在
      const exists = await Dish.exists(dishId)
      if (!exists) {
        return res.status(404).json({
          code: 0,
          msg: '菜品不存在',
          data: null,
        })
      }

      await Dish.delete(dishId)

      res.json({
        code: 1,
        msg: 'success',
        data: null,
      })
    } catch (error) {
      console.error('删除菜品出错:', error)
      res.status(500).json({
        code: 0,
        msg: '删除菜品失败',
        data: null,
      })
    }
  },
}

module.exports = dishController
